package cn.aiseminar.aisinterphone;

import java.io.IOException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class MessageActivity extends Activity {
	private PhoneMessageAdapter mMessageAdapter = null;
	private BluetoothPhoneService mPhoneService = null;
	
	private MediaRecorder mRecorder = null;
	private static String mFileName = null;
	private MediaPlayer mPlayer = null;
	
	@SuppressLint("HandlerLeak")
	private final Handler mMessageHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what)
			{
			case BluetoothPhoneService.MSG_CONTENT_READED:
				byte[] readBuf = (byte[]) msg.obj;
				int readBytes = msg.arg1;
				String message = new String(readBuf, 0, readBytes);
				addToMessageList(message, PhoneMessageAdapter.SENDER_TYPE_THAT);
				break;
			case BluetoothPhoneService.MSG_CONTENT_WRITED:
				break;
			case BluetoothPhoneService.MSG_DEVICE_DISCONNECTED:
				Toast.makeText(MessageActivity.this, R.string.msg_device_disconnected, Toast.LENGTH_LONG).show();
				MessageActivity.this.finish();
				break;
			}
			super.handleMessage(msg);
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.message_activity);
		
		mPhoneService = BluetoothPhoneService.getBluetoothPhoneService();
		mPhoneService.setMsgHandler(mMessageHandler);
				
		ListView messageListView = (ListView)this.findViewById(R.id.lvMessages);
		mMessageAdapter = new PhoneMessageAdapter(this, null);
		messageListView.setAdapter(mMessageAdapter);
		messageListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				hiddenSoftInput();
			}			
		});
		
		Button sendBtn = (Button) this.findViewById(R.id.btn_send);
		sendBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				sendMessage();
			}
		});
		
//        ImageButton recordBtn = (ImageButton)this.findViewById(R.id.btnSpeaking);
//        recordBtn.setOnTouchListener(new View.OnTouchListener() {
//			
//			@Override
//			public boolean onTouch(View v, MotionEvent event) {
//				int action = event.getActionMasked();
//				switch (action)
//				{
//				case MotionEvent.ACTION_DOWN:
//					onBtnPlay(false);
//					onBtnRecord(true);
//					break;
//				case MotionEvent.ACTION_UP:
//					onBtnRecord(false);
//					onBtnPlay(true);
//					break;
//				}
//				return false;
//			}
//		});
	}
		
	@Override
	protected void onStop() {
		mPhoneService.stopTransferData();
		super.onStop();
	}

	public Handler getMessageHandler() {
		return mMessageHandler;
	}
	
	public void addToMessageList(String message, int senderType)
	{
		if (null == message || message.isEmpty())
		{
			return;
		}
		
		mMessageAdapter.add(message, senderType);
		
		ListView messageListView = (ListView)this.findViewById(R.id.lvMessages);
		messageListView.setSelection(messageListView.getCount() - 1);
	}
	
	public void sendMessage()
	{
		EditText edt = (EditText)this.findViewById(R.id.edtMessage);
		String message = edt.getText().toString();
		if (message.isEmpty())
		{
			return;
		}
		mPhoneService.sendMessageToRemote(message);
		mMessageAdapter.add(message, PhoneMessageAdapter.SENDER_TYPE_THIS);
		
		ListView messageListView = (ListView)this.findViewById(R.id.lvMessages);
		messageListView.setSelection(messageListView.getCount() - 1);
		
		edt.setText("");
	}
	
	public void hiddenSoftInput()
	{
		EditText edt = (EditText)this.findViewById(R.id.edtMessage);
//		edt.clearFocus();
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(edt.getWindowToken(),0);
	}
	
	/**
	 * For audio message record & transfer
	 */
	@Override
	protected void onPause() {
		super.onPause();
        if (mRecorder != null) {
            mRecorder.release();
            mRecorder = null;
        }

        if (mPlayer != null) {
            mPlayer.release();
            mPlayer = null;
        }
	}
	
	@SuppressWarnings("unused")
	private void onBtnRecord(boolean start)
	{
		if (start)
		{
			mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
	        mFileName += "/AISInterphoneVoice.3gp";
	        
			startRecording();
		}
		else
		{
			stopRecording();
			// send audio file
		}
	}

	private void startRecording() 
	{        
		mRecorder = new MediaRecorder();
		mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
		mRecorder.setOutputFile(mFileName);
		mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
		try
		{
			mRecorder.prepare();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		mRecorder.start();
	}

	private void stopRecording() 
	{
		if (null != mRecorder)
		{
			mRecorder.stop();
			mRecorder.release();
			mRecorder = null;
		}
	}
	
	@SuppressWarnings("unused")
	private void onBtnPlay(boolean start)
	{
		if (start)
		{
			startPlaying();
		}
		else
		{
			stopPlaying();
		}
	}

	private void startPlaying() 
	{
		mPlayer = new MediaPlayer();
		try
		{
			mPlayer.setDataSource(mFileName);
			mPlayer.prepare();
			mPlayer.start();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	private void stopPlaying() 
	{
		if (null != mPlayer)
		{
			mPlayer.release();
			mPlayer = null;		
		}
	}
}
